//
//  recognize.c
//  FastPRDemo
//
//  Created by fanwenjie on 2017/6/6.
//  Copyright © 2017年 fanwenjie. All rights reserved.
//
#include <stdlib.h>
#include "fastpr.h"
#include "utility.h"
#include "detect.h"
#include "cnn.h"
#include "cnn.gen.h"

const static unsigned short ch0[] = u"京沪津渝冀晋蒙辽吉黑苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新";

const static unsigned short ch1to6[] = u"ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";

const static unsigned short ch7[] = u"\0x0000";

const static unsigned short *charmap[] = {ch0,ch1to6,ch1to6,ch1to6,ch1to6,ch1to6,ch1to6,ch7};

char FastprRecognize(const unsigned char *grayImage, const short width, const short height, short outRegion[4], unsigned short outResult[8])
{
    Rect detectRegion = Detect(grayImage, width, height);
    if(*(unsigned long long *)&detectRegion)
    {
        if(outRegion)
            *(Rect *)outRegion = detectRegion;
        unsigned char *smallImage = (unsigned char *)malloc(detectRegion.width * detectRegion.height);
        image_t normalImage = { 0 };
        CropImage(grayImage, smallImage, width, detectRegion.width, detectRegion.height, detectRegion.x, detectRegion.y);
        ImageResize(smallImage, detectRegion.width, detectRegion.height, IMAGE_WIDTH, IMAGE_HEIGHT, (unsigned char *)normalImage);
        free(smallImage);
        int result[8] = { 0 };
        CNNPredict((const CNN *)cnn, normalImage, result);
        for(int i = 0;i < 7; ++i)
            outResult[i] = charmap[i][result[i]];
        outResult[7] = 0;
        return 1;
    }
    return 0;
}
